<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { ElRow, ElCol, ElCard, ElSkeleton } from 'element-plus'
import { Echart } from '@/components/Echart'
import { selectionType } from '@/api/login/types'
import { getUserListApi } from '@/api/department'
import { ref, reactive, unref } from 'vue'
import { GetPlansApi } from '@/api/course'
import { set } from 'lodash-es'
import { EChartsOption } from 'echarts'
import { useI18n } from '@/hooks/web/useI18n'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { Table, TableColumn } from '@/components/Table'
import * as XLSX from 'xlsx'
const { t } = useI18n()

const loading = ref(true)
const columns: TableColumn[] = [
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'courseName',
    label: '课程名称',
    sortable: true
  },
  {
    field: 'planUserCount',
    label: '计划培训人数',
    sortable: true
  },

  {
    field: 'examUserCount',
    label: '实际培训人数',
    sortable: true
  },
  {
    field: 'examResult',
    label: '考试状态',
    sortable: true
  }
]

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'courseName',
    label: '课程名称',
    component: 'Input'
  },
  {
    field: 'planStatus',
    label: '培训状态',
    component: 'Select',
    componentProps: {
      placeholder: '请选择培训状态'
    },
    optionApi: () => {
      return [
        { label: '已完成', value: 1 },
        { label: '未完成', value: 0 }
      ]
    }
  },
  {
    field: 'examStatus',
    label: '考试状态',
    component: 'Select',
    componentProps: {
      placeholder: '请选择培考试状态'
    },
    optionApi: () => {
      return [
        { label: '已考试', value: 1 },
        { label: '未考试', value: 0 }
      ]
    }
  },
  {
    field: 'date',
    label: t('problem.time'),
    component: 'DatePicker',
    componentProps: {
      style: { width: '340px' },
      type: 'datetimerange',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      StartPlaceholder: 'Start date',
      EndPlaceholder: 'End date'
    }
  }
])
const searchParams = ref({})
const setSearchParams = (params: any) => {
  if (params.date) {
    params.startTime = params.date[0]
    params.endTime = params.date[1]
    delete params.date
  }
  if (params.userNo) {
    params.userNo = params.userNo.toString()
  }
  searchParams.value = params
  getAllApi()
}
const handleColors = () => {
  let color = ''
  let r = Math.floor(Math.random() * 256)
  let g = Math.floor(Math.random() * 256)
  let b = Math.floor(Math.random() * 256)
  color = `rgb(${r},${g},${b})`
  return color
}
const colorHex = (string) => {
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
  if (/^(rgb|RGB)/.test(string)) {
    var aColor = string.replace(/(?:\(|\)|rgb|RGB)*/g, '').split(',')
    var strHex = '#'
    for (var i = 0; i < aColor.length; i++) {
      var hex = Number(aColor[i]).toString(16)
      if (hex === '0') {
        hex += hex
      }
      strHex += hex
    }
    if (strHex.length !== 7) {
      strHex = string
    }
    return strHex
  } else if (reg.test(string)) {
    var aNum = string.replace(/#/, '').split('')
    if (aNum.length === 6) {
      return string
    } else if (aNum.length === 3) {
      var numHex = '#'
      for (var i = 0; i < aNum.length; i += 1) {
        numHex += aNum[i] + aNum[i]
      }
      return numHex
    }
  } else {
    return string
  }
}
const barOptions: EChartsOption = {
  title: {
    text: '课程培训情况表',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    data: ['计划人数', '实际参加人数'],
    top: 25
  },
  grid: {
    left: 50,
    right: 20,
    bottom: 20
  },
  xAxis: {
    type: 'category',
    data: [],
    axisTick: {
      alignWithLabel: true
    }
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '计划人数',
      data: [],
      type: 'bar'
    },
    {
      name: '实际参加人数',
      data: [],
      type: 'bar'
    }
  ]
}

const barOptionsData = reactive<EChartsOption>(barOptions) as EChartsOption
const dataList = ref<tabledt2[]>([])
const getAllApi = async () => {
  const res = await GetPlansApi({ ...unref(searchParams) })

  if (res) {
    dataList.value = res.data

    set(
      barOptionsData,
      'xAxis.data',
      res.data.map((v) => t(v.courseName))
    )
    set(barOptionsData, 'series', [
      {
        name: '计划人数',
        data: res.data.map((v) => v.planUserCount),
        type: 'bar'
      },
      {
        name: '实际参加人数',
        data: res.data.map((v) => v.examUserCount),
        type: 'bar'
      }
    ])
    loading.value = false
  }
}

getAllApi()
interface tabledt {
  课程名称: string
  计划培训人数: number
  实际培训人数: number
  考试状态: string
}
interface tabledt2 {
  courseName: string
  planUserCount: number
  examUserCount: number
  examResult: string
}
const handleData = () => {
  let arr: tabledt[] = []
  dataList.value.map((item) => {
    arr.push({
      课程名称: item.courseName,
      计划培训人数: item.planUserCount,
      实际培训人数: item.examUserCount,
      考试状态: item.examResult
    })
  })
  return arr
}
const exportToExcel = () => {
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new()
  // 创建一个工作表
  const worksheet = XLSX.utils.json_to_sheet(handleData())

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  // 生成Excel文件
  XLSX.writeFile(workbook, '课程培训情况表.xlsx')
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div style="margin-bottom: 10px">
      <BaseButton type="primary" @click="exportToExcel">{{ t('exampleDemo.exprot') }}</BaseButton>
    </div>
    <ElRow :gutter="20" justify="space-between">
      <ElCol :span="24">
        <Table :columns="columns" :data="dataList" :loading="loading" />
      </ElCol>
    </ElRow>
    <div style="margin-top: 20px">
      <ElCol :span="24">
        <Echart :options="barOptionsData" :height="300" />
      </ElCol>
    </div>
  </ContentWrap>
</template>
